using System.Reflection;
using System.Text.Json;
using CoreLib;
using CoreLib.ConfigOptions;
using Domain;
using IdentityModel;
using Infrastructure.RestSharpWrap;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Repository;
using RestSharp;
using Scrutor;
using UI.Models.LayuiResponse;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews()
    ;

builder.Services.Configure<ApproveServiceOptions>(builder.Configuration.GetSection("ApproveService"));
builder.Services.Configure<IdentityServiceOptions>(builder.Configuration.GetSection("IdentityService"));

builder.Services.AddHttpClient()   //  Inject HttpClientFactory
        .AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services
    .AddScoped<IRestClient>(r => new RestClient(builder.Configuration["ApproveService:Host"]))
    .AddScoped<IRestClientExt, RestClientExt>()
    .AddSingleton<ISystemClock, SystemClock>();

builder.Services.ConfigureApplicationCookie(config =>
{
    config.Cookie.Name = "xquant.ids";
    config.LoginPath = "/home/login";
});

builder.Services
    .AddAuthentication(config =>
    {
        config.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        config.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie(options =>
    {
        options.LoginPath = "/home/login";
        options.LogoutPath = "/home/login";
        options.AccessDeniedPath = "/home/login";
    })
    .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, config =>
    {
        config.RequireHttpsMetadata = false;
        config.Authority = builder.Configuration["IdentityService:Host"];
        config.ClientId = "mobileApprove";
        config.ClientSecret = "secret".ToSha256();
        config.SaveTokens = true;
        config.ResponseType = "code";
        config.MetadataAddress = builder.Configuration["IdentityService:Host"] + "/.well-known/openid-configuration";
    })
    ;

builder.Services.Scan(scan =>
{
    scan
        .FromAssemblies(
            Assembly.GetExecutingAssembly(),
            typeof(RepositoryAssembly).Assembly,
            typeof(DomainAssembly).Assembly)
        .AddClasses(classes => classes.Where(t => t.Name.EndsWith("repository", StringComparison.OrdinalIgnoreCase)))
        .UsingRegistrationStrategy(RegistrationStrategy.Skip)   //  TryAdd
        .AsImplementedInterfaces()
        .WithScopedLifetime();
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Login}");

app.Run();
